<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class event_Model_Service extends Zend_Db_Table_Abstract
{
	//only specify the table name, everything else inherits
    	protected $_name = "events";
    	protected $_primary = "id";
    
	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	
	public function findPlaceId($id)
	{
		$sql = "SELECT place_id FROM " . $this->_name . " WHERE id = " . $id;
		$ret = $this->getAdapter()->fetchRow($sql);
	    return $ret;
	}
	
	public function transformToFormArray($formName, $row)
	{	
		$keys = array('frequency','keywords','description','thumb',
					  'id','title', 'status','article_id', 'metadata', 'poster_id', 'city_id', 'district_id', 'village_id');

		$Row = clu_array_merge($keys, $row);
		
		$Row['startHour'] 		= intval($row['start_time']/60);
		$Row['startMinute']		= $row['start_time']%60;
		$Row['finishHour'] 		= intval($row['finish_time']/60);
		$Row['finishMinute']	= $row['finish_time']%60;
		$Row['article_id'] = $row['article_id'];

		if(isset($row['city_id']))
		{
			$keys += array('address5','address6','address7','address8','address9');
			$Row += clu_array_merge($keys, $row);
			$Row['select_place_type'] = unserialize($row['metadata']);
		}
		if($Row['frequency'] == 'weekly')
		{
			$Row['startDay'] 	= $row['start_day'];
			if($row['finish_day'] > 8)
				$Row['finishDay'] 	= $row['finish_day'] - 7;
			else
				$Row['finishDay'] 	= $row['finish_day'];
		}
		else if($Row['frequency'] != 'daily')
		{
			//display dd/mm/YYYY format		
			$startDateArray = explode('/', date_to_string($row['start_date']));
			$finishdateArray = explode('/', date_to_string($row['finish_date']));
			
			//check date/ month/ year of start date
			if(isset($startDateArray['2']) && $startDateArray['2'] == 0)//year = null
			    $Row['startDate'] = $startDateArray['0'] . "/" . $startDateArray['1'];
			else //year != null
			{
				if(isset($startDateArray['0']) && isset($startDateArray['1']) && $startDateArray['0'] == 0)//date = null
					$Row['startDate'] = $startDateArray['1'] . "/" . $startDateArray['2'];
				else
					$Row['startDate'] = date_to_string($row['start_date']);
			}
			//check date/ month/ year of finish date 
			if(isset($finishdateArray['2']) && $finishdateArray['2'] == 0)//year = null
				$Row['finishDate'] 	 = $finishdateArray['0'] . "/" . $finishdateArray['1'];
			else 
			{
				if(isset($finishdateArray['0']) && isset($finishdateArray['1']) && $finishdateArray['0'] == 0)//date = null
					$Row['finishDate'] 	 = $finishdateArray['1'] . "/" . $finishdateArray['2'];
				else
					$Row['finishDate'] 	 = date_to_string($row['finish_date']);
			}
				
			$Row['calendarType'] = $row['calendar_type'];
		}
		
		if($formName == 'edit')
		{
			$mCategory = new category_Model_Category();
            $mCategory->setTables('event');
            $Row['category'] = null;
            foreach($mCategory->getRootType('Root_Event') as $e) {
            	foreach(explode(',', $row['category']) as $tmp)
                	if($e['id'] == $tmp && isset($Row['category_event']))
                		$Row['category_event'] .= $e['name'].',';
                	else
                		$Row['category'] .= $e['name'].',';
            }   
		}
		
		$Row['category_event']    = explode(',', $row['category']);

		$otherFrequency = unserialize($row['metadata']);
		if(isset($otherFrequency['other_frequency']))
			$Row['other_frequency'] = $otherFrequency['other_frequency'];
//		die_a($Row);
		return $Row;
	}
	
	public function insertRaw($data ,$options)
	{ 
		if($options['do_validate'])
    	{
    		$form = new event_Form_Event();
    		if(!$form->isValid($data))
    			return false;
		}
		$e = array();
		$keys = array('frequency','keywords','description','place_id','category',
					  'article_id','title', 'city_id', 'district_id', 'village_id','status',
					  'address5', 'address6', 'address7', 'address8', 'address9', 'metadata' );
		$e = clu_array_merge($keys, $data);
		$e['category']    = implode(',', $data['category_event']);
		$e['start_time']  = $data['startHour']*60 + $data['startMinute'];
		$e['finish_time'] = $data['finishHour']*60 + $data['finishMinute'];
		
		$auth = Zend_Auth::getInstance();
	    $e['poster_id']   = $auth->getIdentity()->id;
		
		if($data['frequency'] == "weekly")
		{		
    		$e['start_day']   = $data['startDay'];
    		if($data['startDay'] > $data['finishDay'] && $data['finishDay'] < 9 )
				$e['finish_day'] 	= $data['finishDay'] + 7;
			else
				$e['finish_day'] 	= $data['finishDay'];
		}
		else 
		{
			if($data['frequency'] != "daily")
    		{
    			$e['calendar_type']   = $data['calendarType'];
        		$e['start_date']  = $this->stringToTime($data['startDate']);
        		$e['finish_date'] = $this->stringToTime($data['finishDate']);
    		}
		}
		$eventMetadata = array(); //metadata
		$eventMetadata['other_frequency'] = $data['other_frequency'];
		//if event belong to some place
		if(!empty($data['belong_to_ids']))
		{
			$e['place_id'] = $data['belong_to_ids'];
			// Because belong_to_ids is place_id and place_name is belong_to_names_submit
			/*
			$eventMetadata['belong_to_ids'] = $data['belong_to_ids'];
			$eventMetadata['belong_to_names'] = $data['belong_to_names_submit'];
			*/
			//add address of Place
			$mPlace = new place_Model_Place();
			$place = $mPlace->findByPrimary($data['belong_to_ids']);
			//still get the city_id, district_id, village_id to update to DB 
			//so that events can be searched by city, district...
			$e['city_id'] = $place['city_id'];
			$e['district_id'] = $place['district_id'];
			$e['village_id'] = $place['village_id'];

			//get metadata from place
			$placeMetadata = unserialize($place['metadata']);
			$eventMetadata['place_name'] = $data['belong_to_names_submit'];//$place['name'];
			if(isset($placeMetadata['city_name'])) 
				$eventMetadata['city_name'] = $placeMetadata['city_name'];
			if(isset($placeMetadata['district_name']))
				$eventMetadata['district_name'] = $placeMetadata['district_name'];
			if(isset($placeMetadata['village_name']))
				$eventMetadata['village_name'] = $placeMetadata['village_name'];
			
	/*		$eventMetadata['place_address5'] = $place['address5'];
			$eventMetadata['place_address6'] = $place['address6'];
			$eventMetadata['place_address7'] = $place['address7'];
			$eventMetadata['place_address8'] = $place['address8'];
			$eventMetadata['place_address9'] = $place['address9'];*/
			$keys = array('address5','address6','address7','address8','address9');
			$eventMetadata += clu_array_merge($keys, $place);
		}
		else //user might have manually added address
		{
			if ($e['city_id'])
			{
				$mCity = new place_Model_City();
		        $cityName = $mCity->getCityName($e['city_id']);
		        $eventMetadata['city_name'] = $cityName['city_name'];
			}
			if ($e['district_id'])
			{
		        $mDistrict = new place_Model_District();
		        $districtName = $mDistrict->getDistrictName($e['district_id']);
		        $eventMetadata['district_name'] = $districtName['district_name'];
			}
			if ($e['village_id'])
			{
		        $mVillage = new place_Model_Village();
		        $villageName = $mVillage->getVillageName($e['village_id']);
		        $eventMetadata['village_name'] = $villageName['village_name'];
			}
		/*    $eventMetadata['event_address5'] = $e['address5'];
			$eventMetadata['event_address6'] = $e['address6'];
			$eventMetadata['event_address7'] = $e['address7'];
			$eventMetadata['event_address8'] = $e['address8'];
			$eventMetadata['event_address9'] = $e['address9'];*/
			$keys = array('address5','address6','address7','address8','address9');
			$eventMetadata += clu_array_merge($keys, $e);
			
		}
		
        $mCategory = new category_Model_Category();
        $mCategory->setTables('event');
        $eventMetadata['category_event_name'] = '';
        foreach($mCategory->getRootType('Root_Event') as $c) {
        	foreach($data['category_event'] as $tmp)
        	{
            	if($c['id'] == $tmp)// && isset($eventMetadata['category_event']))
            	{
            		if($eventMetadata['category_event_name'] == '')
            			$eventMetadata['category_event_name'] .= $c['name'];
            		else
	        			$eventMetadata['category_event_name'] .= ',' .$c['name'];
            	}
        	} 
    	} 
    	//poster_name
		$auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
		$poster_name = $uIdentity->name;
		$eventMetadata['poster_name'] = $poster_name;
		$e['metadata'] = serialize($eventMetadata);
//		die_a($e);
		return $this->insert($e);
	}
	
	public function saveRaw($row, $data, $id,$options )
	{
	    if((!$row) && (!$id))
	    	return false;
	    else if(!$row)
	       	if(!$row = $this->findByPrimary($id))
	       		return false;

	    if ($options['do_validate'])
	    {
	    	//Validate Data here
	    }
		$eventData = array(); //date to update
		$keys = array('frequency','keywords','description','city_id',
					  'district_id', 'village_id','status','title' );
		$eventData = clu_array_merge($keys, $data);
		$eventData['category']    = implode(',', $data['category_event']);
		$eventData['start_time']  = $data['startHour']*60 +$data['startMinute'];
		$eventData['finish_time'] = $data['finishHour']*60 +$data['finishMinute'];
		
		if($data['frequency'] == "weekly")
		{		
    		$eventData['start_day']   = $data['startDay'];
    		if($data['startDay'] > $data['finishDay'] && $data['finishDay'] < 9)
				$eventData['finish_day'] 	= $data['finishDay'] + 7;
			else
				$eventData['finish_day'] 	= $data['finishDay'];
    		$eventData['start_date']  = null;
    		$eventData['finish_date'] = null;
		}
		else 
		{
			if($data['frequency'] != "daily")
    		{
    			$eventData['calendar_type']   = $data['calendarType'];
        		$eventData['start_date']  = $this->stringToTime($data['startDate']);
        		$eventData['finish_date'] = $this->stringToTime($data['finishDate']);
    		}
    		else
    		{
    			$eventData['start_date']  	= null;
        		$eventData['finish_date'] 	= null;
        		$eventData['calendar_type']   = null;
    		}
    		$eventData['start_day']   = null;
			$eventData['finish_day']  = null;
		}
		
		if(!empty($data['belong_to_ids']))
		{
			//update event city_id, district_id, city_id
			$eventData['place_id'] = $data['belong_to_ids'];
			$mPlace = new place_Model_Place();
			$place = $mPlace->findByPrimary($data['belong_to_ids']);
			
			$eventData['city_id'] = $place['city_id'];
			$eventData['district_id'] = $place['district_id'];
			$eventData['village_id'] = $place['village_id'];
			
			$metadata = $this->getMetadata($row, $data);
	/*        $eventData['address5'] = $metadata['event_address5'];
	        $eventData['address6'] = $metadata['event_address6'];
	        $eventData['address7'] = $metadata['event_address7'];
	        $eventData['address8'] = $metadata['event_address8'];
	        $eventData['address9'] = $metadata['event_address9'];*/
	        $keys = array('address5','address6','address7','address8','address9');
			$eventData += clu_array_merge($keys, $metadata);
	        $eventData['metadata'] = serialize($metadata);
		}
		else
		{
			$dbMeta = unserialize($row->metadata);
			if(isset($data['other_frequency']))
			{
				$otherFrequency['other_frequency'] = $data['other_frequency'];
		    	$eventData['metadata'] = serialize($otherFrequency);
			}
	    	else if(isset($dbMeta['other_frequency']))
	    	{
	    		$otherFrequency['other_frequency'] = $dbMeta['other_frequency'];
				$eventData['metadata'] = serialize($otherFrequency);
	    	}
		}   
    	//die_a($eventData); 			
	    $row->setFromArray($eventData);
        return $row->save();
	}
	
	public function getMetadata ($row, $reqData)
	{
		$metadata =array();
        $dbMeta = unserialize($row->metadata);
        $keys = array('place_id','city_name', 'district_name', 'village_name',
        			'belong_to_names', 'distance','category_event_name','poster_name', 'select_place_type'
        			);
       	
       	$mPlace = new place_Model_Place();
        $mCity = new place_Model_City();
        $mDistrict = new place_Model_District();
        $mVillage = new place_Model_Village();
        
        //if user updated "belong_to" => update city, district, village ids & names
		
		if( !empty($reqData['belong_to_ids']))
		{
			$metadata['place_id'] = $reqData['belong_to_ids'];
			$metadata['place_name'] = $reqData['belong_to_names_submit'];
			$placeMetadata = $mPlace->findByPrimary($reqData['belong_to_ids']);
			//city
			if(isset($placeMetadata['city_id']))
			{
				$cityName = $mCity->getCityName($placeMetadata['city_id']);
		        $metadata['city_name'] = $cityName['city_name'];
			}
	        if(isset($placeMetadata['district_id']))
			{
		        $districtName = $mDistrict->getDistrictName($placeMetadata['district_id']);
		        $metadata['district_name'] = $districtName['district_name'];
			}
	        if(isset($placeMetadata['village_id']))
			{
		        $villageName = $mVillage->getVillageName($placeMetadata['village_id']);
		        $metadata['village_name'] = $villageName['village_name'];
			}
			
			//edit address of form event
			if(isset($reqData['address5']))
		        $metadata['event_address5'] = $reqData['address5'];
	    	else if (isset($dbMeta['event_address5']))
	    		$metadata['event_address5'] = $dbMeta['event_address5'];
	    		
	    	if(isset($reqData['address6']))
		        $metadata['event_address6'] = $reqData['address6'];
	    	else if (isset($dbMeta['event_address6']))
	    		$metadata['event_address6'] = $dbMeta['event_address6'];
	    		
	    	if(isset($reqData['address7']))
		        $metadata['event_address7'] = $reqData['address7'];
	    	else if (isset($dbMeta['event_address7']))
	    		$metadata['event_address7'] = $dbMeta['event_address7'];
	    		
	    	if(isset($reqData['address8']))
		        $metadata['event_address8'] = $reqData['address8'];
	    	else if (isset($dbMeta['event_address8']))
	    		$metadata['event_address8'] = $dbMeta['event_address8'];
	    		
	    	if(isset($reqData['address9']))
		        $metadata['event_address9'] = $reqData['address9'];
	    	else if (isset($dbMeta['event_address9']))
	    		$metadata['event_address9'] = $dbMeta['event_address9'];
		}
		//if 
		else
		{
			if(isset($dbMeta['place_id']))
			{
				$metadata['place_id'] = $dbMeta['place_id'];
				//$metadata['belong_to_ids'] = $dbMeta['belong_to_ids'];
				$metadata['place_name'] = $dbMeta['place_name'];
			}
			
			//city
			if (isset($reqData['city_id']))
			{
				$cityName = $mCity->getCityName($reqData['city_id']);
		        $metadata['city_name'] = $cityName['city_name'];
			}	    		
	    	elseif (isset($dbMeta['city_name']))
		    	$metadata['city_name'] = $dbMeta['city_name'];
		    else 
		    	$metadata['city_name'] = null;
		    	
		    //district
			if (isset($reqData['district_id']))
			{
				$districtName = $mDistrict->getDistrictName($reqData['district_id']);
		        $metadata['district_name'] = $districtName['district_name'];
			}	    		
	    	elseif (isset($dbMeta['district_name']))
		    	$metadata['district_name'] = $dbMeta['district_name'];
		    else 
		    	$metadata['district_name'] = null;
		    
		    //village
			if (isset($reqData['village_id']))
			{
				$villageName = $mVillage->getVillageName($reqData['village_id']);
		        $metadata['village_name'] = $villageName['village_name'];
			}	    		
	    	elseif (isset($dbMeta['village_name']))
		    	$metadata['village_name'] = $dbMeta['village_name'];
		    else 
		    	$metadata['village_name'] = null;
		    	
		    	
	       	if(isset($reqData['address5']))
		        $metadata['event_address5'] = $reqData['address5'];
	    	else if (isset($dbMeta['event_address5']))
	    		$metadata['event_address5'] = $dbMeta['event_address5'];
	    		
	    	if(isset($reqData['address6']))
		        $metadata['event_address6'] = $reqData['address6'];
	    	else if (isset($dbMeta['event_address6']))
	    		$metadata['event_address6'] = $dbMeta['event_address6'];
	    		
	    	if(isset($reqData['address7']))
		        $metadata['event_address7'] = $reqData['address7'];
	    	else if (isset($dbMeta['event_address7']))
	    		$metadata['event_address7'] = $dbMeta['event_address7'];
	    		
	    	if(isset($reqData['address8']))
		        $metadata['event_address8'] = $reqData['address8'];
	    	else if (isset($dbMeta['event_address8']))
	    		$metadata['event_address8'] = $dbMeta['event_address8'];
	    		
	    	if(isset($reqData['address9']))
		        $metadata['event_address9'] = $reqData['address9'];
	    	else if (isset($dbMeta['event_address9']))
	    		$metadata['event_address9'] = $dbMeta['event_address9'];
		}
		//poster_name
		if(isset($dbMeta['poster_name']))
		{
			/*
			$auth = Zend_Auth::getInstance();
			$uIdentity = $auth->getIdentity();
			$poster_name = $uIdentity->name;
			$metadata['poster_name'] = $poster_name;
			*/
			$metadata['poster_name'] = $dbMeta['poster_name'];
		}
		
		//event category name
		$mCategory = new category_Model_Category();
        $mCategory->setTables('event');
        $metadata['category_event_name'] = '';
        foreach($mCategory->getRootType('Root_Event') as $c) {
        	foreach($reqData['category_event'] as $tmp)
        	{
            	if($c['id'] == $tmp)// && isset($a['category_event']))
            	{
            		if($metadata['category_event_name'] == '')
            			$metadata['category_event_name'] .= $c['name'];
            		else
	        			$metadata['category_event_name'] .= ',' .$c['name'];
            	}
        	}
    	} 
    	
		if(isset($reqData['other_frequency']))
			$metadata['other_frequency'] = $reqData['other_frequency'];
    	else if(isset($dbMeta['other_frequency']))
    		$metadata['other_frequency'] = $dbMeta['other_frequency'];
    	//die_a($metadata);
        return $metadata;
	}    
	
	//convert string time to integer
	public function stringToTime($data)
	{
		if(!empty($data))
		{
			$countArray = count(split('[/.-]', $data));
			if($countArray > 2)
			{
				list($day, $month, $year ) = split('[/.-]', $data);
				$tmp = (int)$year*500 + (int)$month*35 + (int)$day;
			}
			else
			{
				$value = split('[/.-]', $data);
				if($countArray == 2 && strlen($value['1']) == 4)
				{
					list($month, $year ) = split('[/.-]', $data);
					$tmp = (int)$year*500 + (int)$month*35;
				}
				else
				{
					list($day, $month) = split('[/.-]', $data);
					$tmp = (int)$month*35 + (int)$day;
				}
			}
			return $tmp;
		}
	}
	
	public function search($data)
	{	
     	$startDate		= isset($data['start_date'])   ? string_to_date($data['start_date']) :null;
     	$finishDate		= isset($data['finish_date'])  ? string_to_date($data['finish_date']) :null;
		$keys = array('frequency','keywords','description','category','place_id', 'start_date', 'finish_date',
					  'title','status','calendarType', 'poster_id',  'search_time');
		$e = clu_array_merge($keys, $data);
		//select SQL query
    	$db = $this->getAdapter();
		$select = $db->select();
//				     ->distinct();
		// Add a FROM clause
        $select->from( array('e' => 'events'));
//        die_a($e);
        if($e['title'])
            $select->where('e.title LIKE ?',$db->quoteinto("%".$e['title']."%","STRING"));

        if(isset($data['city_id']) && $data['city_id'] > 0)
            $select->where('e.city_id = ?',$db->quoteinto($data['city_id'],"INTEGER"));

        if(isset($data['district_id']))
        {
			if(count($data['district_id']) > 1)
        	 {
        	 	$s = 0;
	    		foreach($data['district_id'] as $dis)
        	 	{
        	 		$s .= " OR e.district_id = " . (int)$db->quote($dis,"INT");
        	 	}
        	 	$select->where($s);
        	 }
             else
        		$select->where('e.district_id = ?',(int)$db->quote($data['district_id']['0'],"INT"));
		}
            
        if($e['keywords'])
            $select->where('e.keywords LIKE ?',$db->quoteinto("%".$e['keywords']."%","STRING"));
        
        if($e['description'])
            $select->where('e.description LIKE ?',$db->quoteinto("%".$e['description']."%","STRING"));
            
        if($e['status'] && $e['status']  != 'all')
    		$select->where('e.status = ?', $db->quoteinto($e['status'],'STRING'));
    		
    	if($e['poster_id'])
    		$select->where('e.poster_id = ?', (int)$db->quote($e['poster_id'],'INTEGER'));
    		
    	if($e['place_id'])
    		$select->where('e.place_id = ?', (int)$db->quote($e['place_id'],'INTEGER'));

		if($startDate)
        {
        	$select->where('e.start_date >= ?', (int)$db->quote($startDate,"INT"))
	               ->where('e.finish_date <= ?', (int)$db->quote($finishDate,"INT"));
        }
        
    	if(count($e['category'])> 1)
    	{
    		$sql = "0";
            foreach($e['category'] as $c)
               $sql .= " OR " .($db->quoteinto("find_in_set(?,e.category)", $c));
            $select->where($sql);
    	}
    	else if(count($e['category']) == 1)
    		$select->where('e.category = ?', (int)$db->quote($e['category'],'INTEGER'));
    	
    	
//    	$select->join(array('cm' => 'comments'), 'cm.pid' == 'e.id', array('rating', 'rating_count'));
    		
        //frequency & time search
//    	$a =getdate();
//    	$currentTime = $a['mday'] + $a['mon'] * 35 + $a['year'] * 500;
		/*
		if($frequency)
		{
    		switch ($data['frequency'])
        	{
        		case 'once':
        		case 'monthly':
        		case 'yearly':
        		{
        			//search all 'once' events
        			$select->where('e.frequency = ?',$data['frequency']);
        			$select->where('e.start_date >= ?',$startDate)
        					->where('e.finish_date <= ?',$finishDate);
        			break;
        		}
        		case 'daily':
        		{
        			$select->where('e.frequency = ?',"daily");
        			break;
        		}
        		case 'weekly':
        		{
        			$select->where('e.frequency = ?',"weekly");
        			break;
        		}
        	}
		}
		*/
//    	die($select);
        return $select;
	}
	
	public function deleteByPrimary($idArray, $atomic = true)
	{
       	$auth = Zend_Auth::getInstance();
     	$uIdentity = $auth->getIdentity();
     	$sess = new Zend_Session_Namespace(CLU_NS);
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(207);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		$aModel = new article_Model_Service();
        foreach ($idArray as $eventId)
        {
        	$tmp = $this->findByPrimary($eventId)->toArray();
        	$articleIds[]   = $tmp['article_id']; 
        	$posterIds[]	= $tmp['poster_id'];
        }        
		$auth = Zend_Auth::getInstance();
        $db = $this->getAdapter();
        if ($atomic)
	        $db->beginTransaction(); //@NOTE: no effect with MyISAM
        if ((isset($uIdentity->id) != $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete event') === false) || 
            (isset($uIdentity->id) == $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete event') === false))
        {
            return false;
        }
        else 
        {
            try
            {
                $sql = "DELETE FROM events WHERE id IN (". $db->quote($idArray, 'INTEGER') .")" ;
               	$db->query($sql);
                $aModel->deleteByPrimary($articleIds,false); //non atomic
               	if ($atomic)
    	            $db->commit();
                return true;
        	}
            catch (Exception $e)
            {
                if ($atomic)
    	            $db->rollBack();
                return false;
            }
        }
	}
	
	public function bulkUpdateStatus($idArray, $data, $atomic = true)
	{
		$idList = implode (',', $idArray);
		$auth = Zend_Auth::getInstance();
     	$uIdentity = $auth->getIdentity();
     	$sess = new Zend_Session_Namespace(CLU_NS);
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(208);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		$aModel = new article_Model_Service();
        foreach ($idArray as $eventId)
        {
        	$tmp = $this->findByPrimary($eventId)->toArray();
        	$articleIds[]   = $tmp['article_id']; 
        	$posterIds[]	= $tmp['poster_id'];
        }  
		$auth = Zend_Auth::getInstance();
        $db = $this->getAdapter();
        
        if ($atomic)
        	$db->beginTransaction(); //@NOTE: no effect with MyISAM
        
        if ( (isset($uIdentity->id) != $db->quote($posterIds, 'INTEGER') && strpos($sess->userPermissions, 'set status event') === false) || 
            (isset($uIdentity->id) != $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'set status event') === false))
        {
            return false;
        }
        else 
        {
            try
            {
                $sql = "UPDATE events SET status = '".$db->quoteinto($data['status'],"STRING")."' WHERE id IN (".$idList.")" ;
               	$db->query($sql);
                $aModel->bulkUpdateStatus($articleIds,$data,false); //non atomic
                if ($atomic)
	            	$db->commit();
                return true;
        	}
            catch (Exception $e)
            {
            	if ($atomic)
	            	$db->rollBack();
                return false;
            }
        }
	}
	
	public function getData($id, $options)
	{
		if ($event = $this->findByPrimary($id))
		{
			$ret = $event->toArray();
			if ($options['get_article'] == true)
			{
				$article = new article_Model_Service();
				$ret['article'] = $article->getArticleData($event['article_id']);
			}
			return $ret;
		}
		else
			return null;
	}
	
	public function updateDbAfterView($id)
	{
		$sql = sprintf("UPDATE `events` set `views`=`views`+1 WHERE `id`='%d'", $id);
		$db = Zend_Db_Table::getDefaultAdapter();
		$db->query($sql);
	}
	
}
?>
